package com.softpo.encrption;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

//对称加密
//DES（8），AES（16位），3DES（24位）
public class MainActivity extends AppCompatActivity {

    //输入加密的内容，和密码
    private EditText input, pw;
    //显示操作后的内容
    private TextView showInfo;

    //加密的结果
    private String encryptResult = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        input = (EditText) findViewById(R.id.input);
        pw = (EditText) findViewById(R.id.pw);
        showInfo = (TextView) findViewById(R.id.showInfo);
    }

    //加密解密的点击事件
    public void encrypt(View view) {
        String data = input.getText().toString().trim();
        String pw = this.pw.getText().toString().trim();

        //解密的结果
        String decryptResult = null;
        switch (view.getId()) {
            case R.id.desEncrypt://Des加密
                //需要类型，要加密的内容，需要密码
                encryptResult = encrypt("DES", data, pw);
                showInfo.setText("DES加密的内容是： "+data+" ,加密结果是： "+encryptResult);
                break;
            case R.id.desDecrypt://Des解密
                decryptResult = decrypt("DES",encryptResult,pw);
                showInfo.setText("DES解密的结果是： "+decryptResult);
                break;
            case R.id.desedeEncrypt://3DES 加密
                //密码长度24位
                encryptResult = encrypt("DESede",data,pw);
                showInfo.setText("3DES加密的内容是： "+data+" ," +
                        "加密结果是： "+encryptResult);
                break;
            case R.id.desedeDecrypt://3DES 解密
                decryptResult = decrypt("DESede",encryptResult,pw);
                showInfo.setText("3DES解密的结果是： "+decryptResult);
                break;
            case R.id.aesEncrypt://美国军方加密的工具，美国地龙系统
                //16位
                encryptResult = encrypt("AES",data,pw);
                showInfo.setText("AES加密的内容是： "+data+" ," +
                        "加密结果是： "+encryptResult);
                break;
            case R.id.aesDecrypt:
                decryptResult = decrypt("AES",encryptResult,pw);
                showInfo.setText("AES解密的结果是： "+decryptResult);
                break;
        }
    }

    private String decrypt(String type, String data, String pw) {
        Log.d("flag", "----------------->decrypt: Data： " +data+", pw: "+pw);
        switch (type){
            case "DES":
                try {
                    //1、获取解密对应的类,解密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对解密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=8){
                        throw new Exception("密码长度必须是8位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.DECRYPT_MODE,key);

                    //3、执行解密
                    if (!TextUtils.isEmpty(data)) {
                        //Base64逆运算，加密时，为了内容不乱码，进行了Base64编码，
                        //解密的内容，就是经过Base64编码
                        //Base64解码
                        byte[] base64Decode = Base64.decode(data.getBytes(), Base64.DEFAULT);
                        //解密原始内容
                        byte[] decryptBytes = cipher.doFinal(base64Decode);
                       //返回数据
                        return new String(decryptBytes);
                    }
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }


                break;
            case "DESede":
                try {
                    //1、获取解密对应的类,解密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对解密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=24){
                        throw new Exception("密码长度必须是24位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.DECRYPT_MODE,key);

                    //3、执行解密
                    if (!TextUtils.isEmpty(data)) {
                        //Base64逆运算，加密时，为了内容不乱码，进行了Base64编码，
                        //解密的内容，就是经过Base64编码
                        //Base64解码
                        byte[] base64Decode = Base64.decode(data.getBytes(), Base64.DEFAULT);
                        //解密原始内容
                        byte[] decryptBytes = cipher.doFinal(base64Decode);
                        //返回数据
                        return new String(decryptBytes);
                    }
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case "AES":
                try {
                    //1、获取解密对应的类,解密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对解密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=16){
                        throw new Exception("密码长度必须是16位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.DECRYPT_MODE,key);

                    //3、执行解密
                    if (!TextUtils.isEmpty(data)) {
                        //Base64逆运算，加密时，为了内容不乱码，进行了Base64编码，
                        //解密的内容，就是经过Base64编码
                        //Base64解码
                        byte[] base64Decode = Base64.decode(data.getBytes(), Base64.DEFAULT);
                        //解密原始内容
                        byte[] decryptBytes = cipher.doFinal(base64Decode);
                        //返回数据
                        return new String(decryptBytes);
                    }
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            default:
                try {
                    throw  new Exception("加密的类型不匹配，" +
                            "请选择以下几种加密方式：DES，AES，DESede");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;


        }

        return null;
    }

    //加密三种方式
    private String encrypt(String type, String data, String pw) {
        switch (type){
            case "DES":
                try {
                    //1、获取加密对应的类,加密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对加密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=8){
                        throw new Exception("密码长度必须是8位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.ENCRYPT_MODE,key);

                    //3、执行加密
                    if (!TextUtils.isEmpty(data)) {
                        byte[] encryptBytes = cipher.doFinal(data.getBytes());
                        byte[] base64Encode = Base64.encode(encryptBytes, Base64.DEFAULT);
                        return new String(base64Encode);
                    }

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "DESede":
                try {
                    //1、获取加密对应的类,加密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对加密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=24){
                        throw new Exception("密码长度必须是24位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.ENCRYPT_MODE,key);

                    //3、执行加密
                    if (!TextUtils.isEmpty(data)) {
                        byte[] encryptBytes = cipher.doFinal(data.getBytes());
                        byte[] base64Encode = Base64.encode(encryptBytes, Base64.DEFAULT);
                        return new String(base64Encode);
                    }

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "AES":
                try {
                    //1、获取加密对应的类,加密引擎
                    Cipher cipher = Cipher.getInstance(type);

                    //2、对加密引擎进行初始化，指定密码
                    if(pw.getBytes().length!=16){
                        throw new Exception("密码长度必须是16位");
                    }
                    Key key = new SecretKeySpec(pw.getBytes(),type);
                    cipher.init(Cipher.ENCRYPT_MODE,key);

                    //3、执行加密
                    if (!TextUtils.isEmpty(data)) {
                        byte[] encryptBytes = cipher.doFinal(data.getBytes());
                        byte[] base64Encode = Base64.encode(encryptBytes, Base64.DEFAULT);
                        return new String(base64Encode);
                    }

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                try {
                    throw  new Exception("加密的类型不匹配，" +
                            "请选择以下几种加密方式：DES，AES，DESede");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;


        }

        return null;
    }
}
